package kubeclient

import (
	"context"
	"log"

	"k8s.io/apimachinery/pkg/runtime"
	ctrl "sigs.k8s.io/controller-runtime"
	"sigs.k8s.io/controller-runtime/pkg/client"

	appv1 "gitee.com/amoyx/devops-infras/api/v1"
)

var kclient client.Client

func init() {
	kclient = GetClient()
}

func GetClient() client.Client {
	scheme := runtime.NewScheme()
	appv1.AddToScheme(scheme)
	kubeconfig := ctrl.GetConfigOrDie()
	controllerClient, err := client.New(kubeconfig, client.Options{Scheme: scheme})
	if err != nil {
		log.Fatal(err)
		return nil
	}
	return controllerClient
}

func CreateCrd(obj client.Object) error {
	return kclient.Create(context.TODO(), obj)
}

func ListCrd(list client.ObjectList, listOpt client.ListOptions) error {
	return kclient.List(context.TODO(), list, &listOpt)
}

func GetCrd(obj client.Object) error {
	return kclient.Get(context.TODO(), client.ObjectKeyFromObject(obj), obj)
}

func DeleteCrd(obj client.Object) error {
	return kclient.Delete(context.TODO(), obj)
}
